/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.uerj.jms.banco;

import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import model.fabrica.FabricaDeConexao;

/**
 *
 * @author Felipe
 */
public class SubscriberBanco {

    /**
     * Método que escuta a pergunta do usuário
     *
     * @throws NamingException
     * @throws JMSException
     * @throws Exception
     */
    public static void receberMensagem() throws NamingException, JMSException, Exception {

        InitialContext ic = new InitialContext();
        TopicConnectionFactory factory = (TopicConnectionFactory) ic.lookup("jms/Fabrica");
        Topic topic = (Topic) ic.lookup("jms/tabelas");
        TopicConnection connection = factory.createTopicConnection();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        MessageConsumer receiver = session.createConsumer(topic, "(modo = 'pergunta')");
        connection.start();
        System.out.println("LOG: Banco aguardando mensagens...");
        TextMessage message = (TextMessage) receiver.receive();
        String conteudo = message.getText();
        receiver.close();
        session.close();
        connection.close();
        FabricaDeConexao.consulta(conteudo);
    }
}
